package com.xpec.c4.db.log;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xpec.c4.db.model.log.basic.BasicLogModel;
import com.xpec.c4.game.time.JobExecutor;

/**
 * 存放日志对象的缓冲池
 * 
 * @author zhongzhengkai 2011 2011-11-25
 */
public class LogModelPool {

	private static final Log log = LogFactory.getLog(LogModelPool.class);
	
	/**
	 * add接口上一次被调用且执行了SaveLogTask的时间 zhongzhengkai 2011 2011-11-25
	 */
	private static long previousCallTime;

	/**
	 * 使用队列来作为缓冲池
	 */
	private static Queue<BasicLogModel> logPool = new ArrayBlockingQueue<BasicLogModel>(LogPoolConstants.POOL_SIZE*4);

	/**
	 * 从队列头推出一个对象
	 * 
	 * @return Model对象
	 */
	public static BasicLogModel poll() {
		return logPool.poll();
	}

	/**
	 * 往队列尾部压入一个Model对象
	 * 
	 * @param obj
	 *            Model对象
	 */
	public static void add(BasicLogModel obj) {
		
		try
		{
			logPool.add(obj);
		}
		catch(Exception e)
		{
			log.error("add log:" + e);
			return;
		}
		
		long time = System.currentTimeMillis();
		
		// LogModelPool类调用add接口时触发SaveLogTask启动的最短时间
		if ((logPool.size() >= LogPoolConstants.POOL_SIZE)
				|| (logPool.size() > 0 && (time - LogModelPool.previousCallTime >= LogPoolConstants.TIME_SPAN))) {
			LogModelPool.previousCallTime = time;
			JobExecutor.execute(new SaveLogTask());
		}
	}

	/**
	 * @return the dealSize
	 */
	public static int getPoolSize() {
		return logPool.size();
	}
}
